﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CsharpStats.Utils
{
    public class WordStatistics
    {
        // 统计单词出现次数
        public Dictionary<string, int> GetWordFrequency(string[] lines)
        {
            var wordCount = new Dictionary<string, int>();

            foreach (var line in lines)
            {
                var words = Regex.Split(line, @"\W+").Where(w => !string.IsNullOrEmpty(w));

                foreach (var word in words)
                {
                    if (wordCount.ContainsKey(word))
                    {
                        wordCount[word]++;
                    }
                    else
                    {
                        wordCount.Add(word, 1);
                    }
                }
            }

            // 按照单词出现次数降序排序
            wordCount = wordCount.OrderByDescending(w => w.Value).ToDictionary(w => w.Key, w => w.Value);

            return wordCount;
        }
    }
}
